package com.qs.eggs.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.qs.eggs.R;
import com.tencent.mm.sdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.sdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.conn.util.InetAddressUtils;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

public class WXPayActivity extends Activity{
	
	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	private IWXAPI api;
	StringBuffer sb;
	Map<String,String> resultunifiedorder;
	PayReq req;
	
	GetPrepayIdTask mTask ;

	private TextView product_subject;
	private TextView product_price;
	private String orderNo = "";
	private String orderMoney = "";
    private String orderId = "" ;
	private String custid="";
	public static Activity instance;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay);
		instance=this;
		req = new PayReq();
		sb = new StringBuffer();
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);

		initView();
		Button appayBtn = (Button) findViewById(R.id.appay_btn);
		appayBtn.setOnClickListener(new View.OnClickListener() {

		
			@Override
			public void onClick(View v) {

				mTask = new GetPrepayIdTask();
				mTask.execute();
			}
		});		
	}

	private void initView() {
		// TODO Auto-generated method stub
		Intent in = getIntent();
		orderNo = in.getStringExtra("orderNo");
		orderMoney = in.getStringExtra("orderMoney");
		orderId = in.getStringExtra("orderNo");
		SharedPreferences preferences=getSharedPreferences("orderinfo",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor=preferences.edit();
		editor.putString("orderNo",orderNo);
		editor.putString("orderMoney",orderMoney);
		editor.commit();
		product_subject = (TextView) findViewById(R.id.product_subject);
		product_price = (TextView) findViewById(R.id.product_price);
		product_subject.setText(orderNo);
		product_price.setText(Double.parseDouble(orderMoney) + "元");
		product_price.setTag(orderMoney);
	}

	private void goToGetMsg() {
		Intent intent = new Intent(this, GetFromWXActivity.class);
		intent.putExtras(getIntent());
		startActivity(intent);
		finish();
	}
	
	private void goToShowMsg(ShowMessageFromWX.Req showReq) {
		WXMediaMessage wxMsg = showReq.message;		
		WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
		
		StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
		msg.append("description: ");
		msg.append(wxMsg.description);
		msg.append("\n");
		msg.append("extInfo: ");
		msg.append(obj.extInfo);
		msg.append("\n");
		msg.append("filePath: ");
		msg.append(obj.filePath);
		
		Intent intent = new Intent(this, ShowFromWXActivity.class);
		intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
		intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
		intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
		startActivity(intent);
		finish();
	}

	/**
	 生成签名
	 */

	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion1","----"+packageSign);
		return packageSign;
	}
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

		this.sb.append("sign str\n"+sb.toString()+"\n\n");
		
		Log.e("orion","7----"+sb.toString());

		String appSign = MD5.getMessageDigest(sb.toString().getBytes());
		appSign = Change(appSign);
		Log.e("orion","1----"+appSign);
		return appSign;
	}
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");

			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");

		Log.e("orion","2----"+sb.toString());
		return sb.toString();
	}

	//利用access_token，以及partnerid和APP_KEY生成预支付订单
	
	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {

		private ProgressDialog dialog;


		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(WXPayActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
		}

		@Override
		protected void onPostExecute(Map<String,String> result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			//wx201612151033144eef5095160739546060
			sb.append("prepay_id\n"+result.get("prepay_id")+"\n\n");
//			show.setText(sb.toString());
//			dialog = ProgressDialog.show(WXPayActivity.this, getString(R.string.app_tip),
//					sb.toString());
			resultunifiedorder=result;

			genPayReq();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String,String>  doInBackground(Void... params) {

			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			//生成的支付订单
			String entity = genProductArgs();

			Log.e("orion","3----"+entity);
			//把生成的支付订单post生成预付单
			byte[] buf = Util.httpPost(url, entity);

			System.out.println("______________"+buf.toString());
			String content = new String(buf);
			Log.e("orion", "4----"+content);
			Map<String,String> xml=decodeXml(content);

			return xml;
			
			
		}
	}
	

public static Map<String, String> parseXml(HttpServletRequest request)

throws Exception { 

    // 解析结果存储在HashMap 

    Map<String, String> map = new HashMap<String, String>(); 

    InputStream inputStream = request.getInputStream(); 

    // 读取输入流 

    SAXReader reader = new SAXReader();

    Document document = reader.read(inputStream);

    // 得到xml根元素 

    Element root = document.getRootElement();

    // 得到根元素的所有子节点 

    List<Element> elementList = root.elements(); 


    // 遍历所有子节点 

    for (Element e : elementList) 

        map.put(e.getName(), e.getText()); 

    // 释放资源 

    inputStream.close(); 

    inputStream = null; 


    return map; 

} 
	

	public Map<String,String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName=parser.getName();
				switch (event) {
				case XmlPullParser.START_DOCUMENT:

					break;
				case XmlPullParser.START_TAG:

					if("xml".equals(nodeName)==false){
						//实例化student对象
						xml.put(nodeName,parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion","5----"+e.toString());
		}
		return null;

	}


	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}

	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}


	//
	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();

		try {
			String	nonceStr = genNonceStr();

		xml.append("</xml>");
		List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
		packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));//微信分配的公众账号ID
		packageParams.add(new BasicNameValuePair("body", orderNo));//商品或支付单简要描述
		packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));//微信支付分配的商户号
		packageParams.add(new BasicNameValuePair("nonce_str", Change(nonceStr)));//随机字符串，不长于32位。推荐随机数生成算法
		packageParams.add(new BasicNameValuePair("notify_url", "http://124.130.131.94:8087/order/payOrder1.do"));//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
		packageParams.add(new BasicNameValuePair("out_trade_no",orderNo));//商户系统内部的订单号
		packageParams.add(new BasicNameValuePair("spbill_create_ip",getLocalHostIp()));//APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
		int paymoney=(int)(Double.valueOf(orderMoney)*100);
		packageParams.add(new BasicNameValuePair("total_fee",paymoney+""));//订单总金额，单位为分
		packageParams.add(new BasicNameValuePair("trade_type", "APP")); //交易类型

		String sign = genPackageSign(packageParams);
		packageParams.add(new BasicNameValuePair("sign", sign)); //签名

		String xmlstring =toXml(packageParams);

		return	new String(xmlstring.toString().getBytes(), "ISO8859-1");
	//	return xmlstring;

		} catch (Exception e) {
			return null;
		}


	}

	// 生成签名参数
	private void genPayReq() {
		
		req.appId = Constants.APP_ID;
		req.partnerId = Constants.MCH_ID;
		req.prepayId = resultunifiedorder.get("prepay_id");
		req.packageValue = "Sign=WXPay"; 
		req.nonceStr = genNonceStr();
		req.timeStamp = String.valueOf(genTimeStamp());
		
		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
	//	signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		req.sign = genAppSign(signParams);
		
		sb.append("sign\n"+req.sign+"\n\n");

		Log.e("orion==", "6----"+signParams.toString());

		sendPayReq();
	}

	private void sendPayReq() {

		api.registerApp(Constants.APP_ID);
		
		api.sendReq(req);
	}
	
	
	
    

 // 得到本机ip地址
     public String getLocalHostIp()
     {
         String ipaddress = "";
         try
         {
             Enumeration<NetworkInterface> en = NetworkInterface
                     .getNetworkInterfaces();
             // 遍历所用的网络接口
             while (en.hasMoreElements())
             {
                 NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
                 Enumeration<InetAddress> inet = nif.getInetAddresses();
                 // 遍历每一个接口绑定的所有ip
                 while (inet.hasMoreElements())
                 {
                     InetAddress ip = inet.nextElement();
                     if (!ip.isLoopbackAddress()
                             && InetAddressUtils.isIPv4Address(ip
                                     .getHostAddress()))
                     {
                         return ipaddress = ip.getHostAddress();
                     }
                 }

             }
         }
         catch (SocketException e)
         {
             Log.e("feige", "获取本地ip地址失败");
             e.printStackTrace();
         }
         return ipaddress;

     }
    
    //小写转大写
     public static String Change(String str) {
   //     str = "ABC123abcfadfjbJBHJHJDsa";  
         StringBuffer sb = new StringBuffer();  
         int i;  
         for(i = 0; i <= str.length()-1;i ++){//遍历字符串  
             char ch;  
             //通过str.charAt(i)遍历出字符串中每个字符  
             if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z'){//判断字符是否在a-z之间（小写）  
                 ch = (char) (str.charAt(i)-32);               //如果为小写则转换为相应大写,赋值给ch  
             }else if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){//判断字符是否在A-Z之间（大写）  
                 ch = (char) (str.charAt(i)+32);               //如果为大写则转换为相应小写,赋值给ch  
             }else if(str.charAt(i)>='0'&&str.charAt(i)<='9'){//判断字符是否在0-9之间（数字）  
                   ch = str.charAt(i);                         //如果为数字,将原数字赋值给ch  
             }else {  
                   ch = '*';                                   //如果为其他则转为*号  
             }  
             sb.append(ch);                                    //将字符追加到sb序列  
           }                        
         System.out.println(sb.toString()); //将StringBuffer转换为String类型  
		return sb.toString();
    }



}
